<?php


namespace App\Services;


use App\Model\GroupUser;
use Carbon\Carbon;
use Swoole\WebSocket\Frame;

class GroupService
{

    public static function send(Frame $frame, $server, array $message)
    {
        $from_user = redis()->hGet('im_user_online', (string)$frame->fd);

        $target_group_users = GroupUser::query()
            ->select('user_id')
            ->where('group_id', $message['target_group_id'])
            ->get();

        $msgData = [
            'action' => 'msg_from_group',
            'message' => [
                'time' => Carbon::now(),
                'type' => 0,
                'body' => $message['message']['body'],
            ],
            'from_user' => [
                'id' => $from_user
            ],
            'target_group' => [
                'id' => $message['target_group_id']
            ]
        ];

        foreach ($target_group_users as $k => $v) {
            $userFd = redis()->hGet('user_id_to_fd', (string)$v->user_id);

            if (is_bool($userFd)) {
                continue;
            }

            if ($server->isEstablished((int)$userFd)) {
                $server->push($userFd, json_encode($msgData, 256));
            }
        }
    }
}